<?php
if($_GET['id'] == 16){
	header("Location: old.php?page=education");
	exit();
}
$db = Db::getInstance();
try {
	if($_SERVER['REQUEST_METHOD'] == 'POST') {
		if(!Authenticate::isLogin()){
			throw new Exception('กรุณา Login ก่อนสั่งซื้อ', 200);
		}
		$sessionBuy = array();
		$optional = array();

		$package = Package::instance()->getOne(array('id'=> $_POST['packageId'], 'status'=> 1));
		if(!$package) {
			throw new Exception('Not found package');
		}
		$price = Price::instance()->getOne(array('id'=> $_POST['priceId']));

		$sessionBuy['package'] = $package;
		$sessionBuy['price'] = $price;
		$sessionBuy['info'] = $package['info'];

		$sessionBuy['priceAll'] = 0;

		$date = new DateTime();
		$dateDue = new DateTime();
		$dateDue->add(new DateInterval('P7D'));
		$sessionBuy['dateCreate'] = $date->format('Y-m-d');
		$sessionBuy['dateDue'] = $dateDue->format('Y-m-d');

		if($package['type'] == 'vps'){
			$sessionBuy['os'] = $_POST['os'];
            $sessionBuy['info'] .= "\n - OS ".($_POST['os']==2? 'Linux': 'Window');
		}
		else if($package['type'] == 'hosting'){
			$sessionBuy['domain'] = $_POST['domain'];
            $sessionBuy['info'] .= "\n - Domain ".$_POST['domain'];
		}
		
		function genSessionCode()
		{
			$code = md5(rand(1000, 100000));
			if(!isset($_SESSION['confirmBuyCode'])){ $_SESSION['confirmBuyCode'] = array(); }
			if(isset($_SESSION['confirmBuyCode'][$code]))
				return genSessionCode();
			else
				return $code;
		}
		
		$sessionCode = genSessionCode();
		$_SESSION['confirmBuyCode'][$sessionCode] = $sessionBuy;
		
		View::display('confirm.buyPackage', array('sessionBuy'=> $sessionBuy, 'sessionCode'=> $sessionCode));
	}
	else {
        $package = Package::instance()->getOne(array('id'=> $_GET['id'], 'status'=> 1));
        $package['prices'] = Price::instance()->get(array('packageId'=> $_GET['id']));
		if(!$package){
			throw new Exception('Not found package');
		}
		View::display('buyPackage', array('package'=> $package));
	}
} catch (Exception $ex){
	if($ex->getCode() == 200){
		View::display('message',
		array(
			'head'=> 'คุณยังไม่ได้ Login', 'message'=> $ex->getMessage(),
			'redir'=> $_SERVER['REQUEST_URI'], 'sec'=> 4
		));
	}
	else {
		Log::error($ex);
		View::display('error', array('message' => $ex->getMessage()));
		throw $ex;
	}
}